﻿using MesBSW.DAL.MesDB;
using MesBSW.DAL.MesDTO;
using MesBSW.DAL.RoleDB;
using MesBSW.Tools;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace MesBSW.BLL.Mes
{
    public class ProdProcScanControler : BaseControler
    {
        /// <summary>
        /// 根据站点，查询工单在站点的扫码总数量
        /// </summary>
        /// <param name="prod"></param>
        /// <param name="siteID"></param>
        /// <returns></returns>
        public decimal GetProdScanQtyForSite(string prod, int siteID)
        {
            decimal resDec = 0;
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.ProdProcScans.Where(q => q.ProdNumber == prod && q.SiteInfoID == siteID);
                if (query != null && query.Count() > 0)
                {
                    resDec = query.Sum(q => q.ScanQty);
                }
            }
            return resDec;
        }

        /// <summary>
        /// 通过工单单号查询扫码记录
        /// </summary>
        /// <param name="prodNo"></param>
        /// <returns></returns>
        public List<ProdProcScan> SearchScanForProdNumber(string prodNo)
        {
            List<ProdProcScan> resList = new List<ProdProcScan>();
            using (MesDB ctx = new MesDB())
            {
                var query = ctx.ProdProcScans.Where(s => s.ProdNumber == prodNo).OrderBy(s => s.ScanDate);
                if (query != null && query.Count() > 0)
                {
                    resList.AddRange(query);
                }
            }
            return resList;
        }

        //BaseControler bs = new BaseControler();
        ///// <summary>
        ///// 查询所有父站点，并将子站点一并查询出来
        ///// </summary>
        ///// <returns></returns>
        //public List<SiteInfoDTO> SearchParentSite()
        //{
        //    List<SiteInfoDTO> resList = new List<SiteInfoDTO>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        var query = ctx.SiteInfos;
        //        if (query != null && query.Count() > 0)
        //        {
        //            var parQuery = query.ToList().Where(p => p.ParentID == 0);
        //            if (parQuery != null && parQuery.Count() > 0)
        //            {
        //                foreach (var parItem in parQuery)
        //                {
        //                    SiteInfoDTO par = new SiteInfoDTO();
        //                    EntityTools.CopyEntity(parItem, ref par);

        //                    var childQuery = query.Where(c => c.ParentID == parItem.ID);
        //                    if (childQuery != null && childQuery.Count() > 0)
        //                    {
        //                        par.ChildSiteList = new List<SiteInfo>();
        //                        foreach (var childItem in childQuery)
        //                        {
        //                            SiteInfo child = new SiteInfo();
        //                            EntityTools.CopyEntity(childItem, ref child);
        //                            par.ChildSiteList.Add(child);
        //                        }
        //                    }

        //                    resList.Add(par);
        //                }
        //            }
        //        }
        //        if (query != null && query.Count() > 0)
        //        {



        //        }
        //    }
        //    return resList;
        //}


        /// <summary>
        /// 查询同一类型的状态
        /// </summary>
        /// <returns></returns>
        public List<StatusInfo> SearchStatusInfoByTypeName(string typeName)
        {
            List<StatusInfo> resList = new List<StatusInfo>();
            using (MesDB ctx = new MesDB())
            {
                var query = from a in ctx.StatusTypes
                            join b in ctx.StatusInfos on a.ID equals b.StypeID into res
                            from ab in res.DefaultIfEmpty()
                            where a.StypeName == typeName
                            select ab;
                if (query != null && query.Count() > 0)
                {
                    foreach (var item in query)
                    {
                        if (item != null && item.ID > 0)
                        {
                            resList.Add(item);
                        }
                    }
                }
            }
            return resList;
        }


        ///// <summary>
        ///// 查询大站中的工单暂停状态
        ///// </summary>
        ///// <param name="prodNo">工单号</param>
        ///// <param name="site">大站点</param>
        ///// <param name="isFause">是否暂停</param>
        ///// <returns></returns>
        //public List<TargetProdProcessDTO> SearchTargetForPause(string prodNo, SiteInfo site, Boolean isFause)
        //{
        //    List<TargetProdProcessDTO> resList = new List<TargetProdProcessDTO>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        List<int> siteList = new List<int>();
        //        var siteQuery = ctx.SiteInfos.Where(s => s.ParentID == site.ID);
        //        if (siteQuery != null && siteQuery.Count() > 0)
        //        {
        //            foreach (var item in siteQuery)
        //            {
        //                siteList.Add(item.ID);
        //            }
        //        }

        //        StatusInfo status = new StatusInfo();
        //        var statusQuery = ctx.StatusInfos.Where(s => s.StatusValue.Equals("暂停"));
        //        if (statusQuery != null && statusQuery.Count() > 0)
        //        {
        //            status = statusQuery.First();
        //        }

        //        var query = from a in ctx.TargetProdProcesses
        //                    join b in ctx.ProdProcSites on a.ID equals b.ProdProcID into res1
        //                    from ab in res1.DefaultIfEmpty()
        //                    join c in ctx.SiteGroups on ab.SiteGroupID equals c.ID into res2
        //                    from bc in res2.DefaultIfEmpty()
        //                    where siteList.Contains(a.CurrSiteID)
        //                    select new { A = a, AB = ab, BC = bc };
        //        if (query != null && query.Count() > 0)
        //        {
        //            foreach (var item in query)
        //            {
        //                TargetProdProcessDTO resTarget = new TargetProdProcessDTO();
        //                EntityTools.CopyEntity<TargetProdProcess, TargetProdProcessDTO>(item.A, ref resTarget);
        //                SiteGroupDTO siteGroup = new SiteGroupDTO();
        //                EntityTools.CopyEntity<SiteGroup, SiteGroupDTO>(item.BC, ref siteGroup);
        //                resTarget.SiteGroup = siteGroup;
        //                resList.Add(resTarget);
        //            }
        //        }

        //        if (prodNo != null && prodNo.Trim().Length > 0)
        //        {
        //            resList = resList.Where(t => t.ProdNumber.Contains(prodNo)).ToList();
        //        }
        //        if (isFause)
        //        {
        //            resList = resList.Where(t => t.ErrStatusID == status.ID).ToList();
        //        }
        //        else
        //        {
        //            resList = resList.Where(t => t.ErrStatusID != status.ID).ToList();
        //        }
        //    }

        //    return resList;
        //}

        /// <summary>
        /// 通过二维码查询工单信息
        /// </summary>
        /// <param name="prodNo">工单号</param>
        /// <returns></returns>
        public TargetProdProcessDTO SearchTargetForScan(string prodNo)
        {
            TargetProdProcessDTO resTarget = null;
            using (MesDB ctx = new MesDB())
            {
                var query = from a in ctx.TargetProdProcesses
                            join b in ctx.ProdProcSites on a.ID equals b.ProdProcID into res1
                            from ab in res1.DefaultIfEmpty()
                            join c in ctx.SiteGroups on ab.SiteGroupID equals c.ID into res2
                            from bc in res2.DefaultIfEmpty()
                            where a.ProdNumber == prodNo
                            select new { A = a, AB = ab, BC = bc };
                if (query != null && query.Count() > 0)
                {
                    resTarget = new TargetProdProcessDTO();
                    EntityTools.CopyEntity<TargetProdProcess, TargetProdProcessDTO>(query.First().A, ref resTarget);
                    if (query.First().BC != null)
                    {
                        SiteGroupDTO siteGroup = new SiteGroupDTO();
                        EntityTools.CopyEntity<SiteGroup, SiteGroupDTO>(query.First().BC, ref siteGroup);
                        resTarget.SiteGroup = siteGroup;

                        var siteQuery = from a in ctx.SiteGroups
                                        join b in ctx.SiteInfoGroups on a.ID equals b.GroupID into res1
                                        from ab in res1.DefaultIfEmpty()
                                        join c in ctx.SiteInfos on ab.SiteID equals c.ID into res2
                                        from bc in res2.DefaultIfEmpty()
                                        where a.ID == resTarget.SiteGroup.ID
                                        orderby ab.Sort
                                        select new { A = a, AB = ab, BC = bc };
                        if (siteQuery != null && siteQuery.Count() > 0)
                        {
                            resTarget.SiteGroup.SiteInfoList = new List<SiteInfoGroupDTO>();
                            foreach (var item in siteQuery)
                            {
                                if (item.AB != null && item.BC != null)
                                {
                                    SiteInfoGroupDTO groupBean = new SiteInfoGroupDTO();
                                    SiteInfo siteBean = new SiteInfo();
                                    EntityTools.CopyEntity(item.BC, ref siteBean);
                                    EntityTools.CopyEntity(item.AB, ref groupBean);
                                    groupBean.SiteInfo = siteBean;
                                    resTarget.SiteGroup.SiteInfoList.Add(groupBean);
                                }
                            }
                        }
                    }
                }
            }
            return resTarget;
        }


        ///// <summary>
        ///// 根据条件查询工单
        ///// </summary>
        ///// <param name="prod">工单号</param>
        ///// <param name="isComp">是否完成</param>
        ///// <param name="urgentList">紧急状态</param>
        ///// <param name="scheduleBeginDay">排单开始日期</param>
        ///// <param name="scheduleEndDay">排单结束日期</param>
        ///// <param name="scanBeginDay">扫码开始日期</param>
        ///// <param name="scanEndDay">扫码结束日期</param>
        ///// <returns></returns>
        //public List<TargetProdProcessDTO> SearchProdProcessWorkTime(string prod, int isComp, List<int> urgentList, DateTime? scheduleBeginDay, DateTime? scheduleEndDay,
        //                                                                DateTime? scanBeginDay, DateTime? scanEndDay)
        //{
        //    List<int> deptIds = bs.SelectUserDept();
        //    List<TargetProdProcessDTO> resList = new List<TargetProdProcessDTO>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        var query = from a in ctx.TargetProdProcesses
        //                    join b in ctx.ProdProcScans on a.ID equals b.ProdProcID into res1
        //                    from ab in res1.DefaultIfEmpty()
        //                    join c in ctx.SourceProdProcesses on a.ParentID equals c.ID into res2
        //                    from ac in res2.DefaultIfEmpty()
        //                    join d in ctx.SourcePPCycle on ac.ID equals d.SourceID into res3
        //                    from cd in res3.DefaultIfEmpty()
        //                    join e in ctx.ProdSchedules.Where(q => (q.LineID == 1 || q.LineID == 13) && q.IsDel == 0).AsQueryable() on a.ID equals e.ProdID into res4
        //                    from ae in res4.DefaultIfEmpty()
        //                    select new { A = a, AB = ab, AC = ac, CD = cd, AE = ae };
        //        query = query.Where(res => res.A.DeptId != 0 && deptIds.Contains(res.A.DeptId));
        //        if (prod != null && prod.Length > 0)
        //        {
        //            query = query.Where(q => q.A.ProdNumber.Contains(prod.Trim()));
        //        }
        //        if (isComp == 1)
        //        {
        //            query = query.Where(q => q.A.CurrSiteID == 20);
        //        }
        //        else if (isComp == 0)
        //        {
        //            query = query.Where(q => q.A.CurrSiteID != 20);
        //        }
        //        if (urgentList != null && urgentList.Count > 0)
        //        {
        //            query = query.Where(q => urgentList.Contains(q.A.UrgentStatusID));
        //        }

        //        if (scheduleBeginDay.HasValue)
        //        {
        //            query = query.Where(q => DbFunctions.TruncateTime(q.AE.FillDate) >= ((DateTime)scheduleBeginDay).Date);
        //        }
        //        if (scheduleEndDay.HasValue)
        //        {
        //            query = query.Where(q => DbFunctions.TruncateTime(q.AE.FillDate) <= ((DateTime)scheduleEndDay).Date);
        //        }

        //        if (scanBeginDay.HasValue)
        //        {
        //            query = from a in query
        //                    join b in ctx.ProdProcScans.Where(q => DbFunctions.TruncateTime(q.ScanDate) >= ((DateTime)scanBeginDay).Date).Select(q => q.ProdNumber).Distinct() on a.A.ProdNumber equals b into res1
        //                    from ab in res1
        //                    select a;
        //        }

        //        if (scanEndDay.HasValue)
        //        {
        //            query = from a in query
        //                    join b in ctx.ProdProcScans.Where(q => DbFunctions.TruncateTime(q.ScanDate) <= ((DateTime)scanEndDay).Date).Select(q => q.ProdNumber).Distinct() on a.A.ProdNumber equals b into res1
        //                    from ab in res1
        //                    select a;
        //        }

        //        if (query != null && query.Count() > 0)
        //        {
        //            var tmpList = query.ToList();
        //            foreach (var item in tmpList.Select(q => q.A).Distinct().OrderBy(q => q.ProdNumber).ToList<TargetProdProcess>())
        //            {
        //                TargetProdProcessDTO targetBean = new TargetProdProcessDTO();
        //                EntityTools.CopyEntity<TargetProdProcess, TargetProdProcessDTO>(item, ref targetBean);

        //                targetBean.scanList = new List<ProdProcScan>();
        //                var scanQuery = tmpList.Where(q => q.AB != null && q.AB.ProdProcID == item.ID);
        //                if (scanQuery != null & scanQuery.Count() > 0)
        //                {
        //                    foreach (var scanItem in scanQuery)
        //                    {
        //                        targetBean.scanList.Add(scanItem.AB);
        //                    }
        //                }

        //                targetBean.scheduleList = new List<ProdSchedule>();
        //                var scheQuery = tmpList.Where(q => q.AE != null && q.AE.ProdID == item.ID);
        //                if (scheQuery != null && scheQuery.Count() > 0)
        //                {
        //                    foreach (var scheItem in scheQuery)
        //                    {
        //                        targetBean.scheduleList.Add(scheItem.AE);
        //                    }
        //                }
        //                resList.Add(targetBean);
        //            }
        //        }
        //    }
        //    return resList;
        //}


        ///// <summary>
        ///// 根据条件查询工单
        ///// </summary>
        ///// <param name="prod">工单号</param>
        ///// <param name="mto">跟踪单号</param>
        ///// <param name="urgentStatus">紧急状态</param>
        ///// <param name="parentSite">大站</param>
        ///// <param name="isBegin">是否已上线</param>
        ///// <param name="isComp">是否已完成</param>
        ///// <param name="cust">客户代号</param>
        ///// <param name="saler">销售员</param>
        ///// <returns></returns>
        //public List<TargetProdProcessDTO> SearchProdProcessForCondition(string prod, string mto, int prodStatus, int urgentStatus, int parentSite, bool isBegin,
        //                                                                        string cust, string saler, int isComp, DateTime beginDay, DateTime endDay)
        //{
        //    List<TargetProdProcessDTO> resList = new List<TargetProdProcessDTO>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        var query = from a in ctx.TargetProdProcesses
        //                    join b in ctx.ProdProcSites on a.ID equals b.ProdProcID into res1
        //                    from ab in res1
        //                    join c in ctx.SiteGroups on ab.SiteGroupID equals c.ID into res2
        //                    from bc in res2
        //                    join d in ctx.SiteInfoGroups on bc.ID equals d.GroupID into res3
        //                    from cd in res3
        //                    join e in ctx.SiteInfos on cd.SiteID equals e.ID into res4
        //                    from de in res4
        //                    join f in ctx.SiteInfos on a.CurrSiteID equals f.ID into res5
        //                    from af in res5.DefaultIfEmpty()
        //                    select new { A = a, AB = ab, BC = bc, CD = cd, DE = de, AF = af };
        //        if (cust != null && cust.Trim().Length > 0)
        //        {
        //            query = query.Where(q => q.A.ClientCode.Contains(cust));
        //        }
        //        if (saler != null && saler.Trim().Length > 0)
        //        {
        //            query = query.Where(q => q.A.SalerName.Contains(saler));
        //        }
        //        if (prod != null && prod.Trim().Length > 0)
        //        {
        //            query = query.Where(q => q.A.ProdNumber.Contains(prod));
        //        }
        //        if (mto != null && mto.Trim().Length > 0)
        //        {
        //            query = query.Where(q => q.A.MtoNumber.Contains(mto));
        //        }
        //        if (prodStatus > 0)
        //        {
        //            query = query.Where(q => q.A.ProdStatusID == prodStatus);
        //        }
        //        if (urgentStatus > 0)
        //        {
        //            query = query.Where(q => q.A.UrgentStatusID == urgentStatus);
        //        }
        //        if (parentSite > 0)
        //        {
        //            query = query.Where(q => q.AF.ParentID == parentSite);
        //        }

        //        List<string> tmpScanList = new List<string>();
        //        if (isComp == 1)
        //        {
        //            var scanQuery = ctx.ProdProcScans.Where(s => beginDay.Date <= DbFunctions.TruncateTime(s.ScanDate) && DbFunctions.TruncateTime(s.ScanDate) <= endDay);
        //            if (scanQuery != null && scanQuery.Count() > 0)
        //            {
        //                tmpScanList = scanQuery.Select(s => s.ProdNumber).Distinct().ToList<string>();
        //            }
        //        }
        //        else if (isComp == 0)
        //        {
        //            query = query.Where(q => q.A.ProdStatusID != 6 && q.A.ProdStatusID != 13);
        //        }
        //        else
        //        {
        //            query = query.Where(q => q.A.ProdStatusID == 13);
        //        }

        //        if (query != null && query.Count() > 0)
        //        {
        //            var item = query.ToList();
        //            var tarQuery = item.Select(q => new { q.A, q.BC }).Distinct();
        //            if (tarQuery != null && tarQuery.Count() > 0)
        //            {
        //                foreach (var tar in tarQuery)
        //                {
        //                    if (isComp == 1)
        //                    {
        //                        if (tmpScanList.Contains(tar.A.ProdNumber) == false)
        //                        {
        //                            continue;
        //                        }
        //                    }
        //                    TargetProdProcessDTO tarBean = new TargetProdProcessDTO();
        //                    EntityTools.CopyEntity(tar.A, ref tarBean);

        //                    SiteGroupDTO groupBean = new SiteGroupDTO();
        //                    if (tar.BC != null && tar.BC.ID > 0)
        //                    {
        //                        EntityTools.CopyEntity(tar.BC, ref groupBean);
        //                        tarBean.SiteGroup = groupBean;

        //                        var siteQuery = item.Where(q => q.A.ProdNumber == tarBean.ProdNumber).OrderBy(q => q.CD.Sort).Select(q => new { q.CD, q.DE });
        //                        if (siteQuery != null && siteQuery.Count() > 0)
        //                        {
        //                            tarBean.SiteGroup.SiteInfoList = new List<SiteInfoGroupDTO>();
        //                            foreach (var site in siteQuery)
        //                            {
        //                                SiteInfoGroupDTO siteGroupBean = new SiteInfoGroupDTO();
        //                                EntityTools.CopyEntity(site.CD, ref siteGroupBean);

        //                                SiteInfo siteBean = site.DE;
        //                                siteGroupBean.SiteInfo = siteBean;
        //                                tarBean.SiteGroup.SiteInfoList.Add(siteGroupBean);
        //                            }
        //                        }
        //                    }
        //                    resList.Add(tarBean);
        //                }
        //            }

        //        }
        //    }
        //    return resList;
        //}

        ///// <summary>
        ///// 查询所有工单
        ///// </summary>
        ///// <returns></returns>
        //public List<TargetProdProcessDTO> SearchAllProdProcess()
        //{
        //    List<TargetProdProcessDTO> resList = new List<TargetProdProcessDTO>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        var query = from a in ctx.TargetProdProcesses
        //                    join b in ctx.ProdProcSites on a.ID equals b.ProdProcID into res1
        //                    from ab in res1
        //                    join c in ctx.SiteGroups on ab.SiteGroupID equals c.ID into res2
        //                    from bc in res2
        //                    join d in ctx.StatusInfos on a.UrgentStatusID equals d.ID into res3
        //                    from cd in res3
        //                    orderby cd.Sort
        //                    select new { A = a, BC = bc };
        //        if (query != null && query.Count() > 0)
        //        {
        //            List<string> prodList = new List<string>();
        //            foreach (var item in query)
        //            {
        //                TargetProdProcessDTO tmpTarget = new TargetProdProcessDTO();
        //                EntityTools.CopyEntity<TargetProdProcess, TargetProdProcessDTO>(item.A, ref tmpTarget);

        //                SiteGroupDTO siteGroup = new SiteGroupDTO();
        //                EntityTools.CopyEntity<SiteGroup, SiteGroupDTO>(item.BC, ref siteGroup);
        //                tmpTarget.SiteGroup = siteGroup;
        //                resList.Add(tmpTarget);

        //                string tmpProd = tmpTarget.ProdNumber.Split('-')[0];
        //                if (prodList.Contains(tmpProd) == false)
        //                {
        //                    prodList.Add(tmpProd);
        //                }
        //            }

        //            var sourceQuery = ctx.SourcePPCycle.Where(s => prodList.Contains(s.ProdNumber));
        //            if (sourceQuery != null && sourceQuery.Count() > 0)
        //            {
        //                List<SourcePPCycle> cycleList = sourceQuery.ToList();
        //                foreach (var item in resList)
        //                {
        //                    var tmpQuery = cycleList.Where(c => c.ProdNumber.Equals(item.ProdNumber.Split('-')[0]));
        //                    if (tmpQuery != null && tmpQuery.Count() > 0)
        //                    {
        //                        item.SourceCycle = tmpQuery.First();
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    return resList;
        //}

        ///// <summary>
        ///// 查询未做完的工单
        ///// </summary>
        ///// <returns></returns>
        //public List<TargetProdProcessDTO> SearchTargetForNoComplete()
        //{
        //    List<TargetProdProcessDTO> resList = new List<TargetProdProcessDTO>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        var query = from a in ctx.TargetProdProcesses
        //                    join b in ctx.ProdProcSites on a.ID equals b.ProdProcID into res1
        //                    from ab in res1
        //                    join c in ctx.SiteGroups on ab.SiteGroupID equals c.ID into res2
        //                    from bc in res2
        //                    join d in ctx.StatusInfos on a.ProdStatusID equals d.ID into res3
        //                    from ad in res3
        //                    where !ad.StatusValue.Equals("未上线") && !ad.StatusValue.Equals("已完成")
        //                    select new { A = a, AB = ab, BC = bc };
        //        if (query != null && query.Count() > 0)
        //        {
        //            foreach (var item in query)
        //            {
        //                TargetProdProcessDTO tmpTarget = new TargetProdProcessDTO();
        //                EntityTools.CopyEntity<TargetProdProcess, TargetProdProcessDTO>(item.A, ref tmpTarget);

        //                SiteGroupDTO siteGroup = new SiteGroupDTO();
        //                EntityTools.CopyEntity<SiteGroup, SiteGroupDTO>(item.BC, ref siteGroup);
        //                tmpTarget.SiteGroup = siteGroup;

        //                var siteQuery = from a in ctx.SiteGroups
        //                                join b in ctx.SiteInfoGroups on a.ID equals b.GroupID into res1
        //                                from ab in res1.DefaultIfEmpty()
        //                                join c in ctx.SiteInfos on ab.SiteID equals c.ID into res2
        //                                from bc in res2.DefaultIfEmpty()
        //                                where a.ID == tmpTarget.SiteGroup.ID
        //                                orderby ab.Sort
        //                                select new { A = a, AB = ab, BC = bc };
        //                if (siteQuery != null && siteQuery.Count() > 0)
        //                {
        //                    tmpTarget.SiteGroup.SiteInfoList = new List<SiteInfoGroupDTO>();
        //                    foreach (var siteItem in siteQuery)
        //                    {
        //                        if (item.AB != null && item.BC != null)
        //                        {
        //                            SiteInfoGroupDTO groupBean = new SiteInfoGroupDTO();
        //                            SiteInfo siteBean = new SiteInfo();
        //                            EntityTools.CopyEntity(siteItem.BC, ref siteBean);
        //                            EntityTools.CopyEntity(siteItem.AB, ref groupBean);
        //                            groupBean.SiteInfo = siteBean;
        //                            tmpTarget.SiteGroup.SiteInfoList.Add(groupBean);
        //                        }
        //                    }
        //                }
        //                resList.Add(tmpTarget);
        //            }
        //        }
        //    }
        //    return resList;
        //}

        ///// <summary>
        ///// 根据多个工单号查询扫码记录
        ///// </summary>
        ///// <param name="prods"></param>
        ///// <returns></returns>
        //public List<ProdProcScan> SearchScanByProds(List<string> prods)
        //{
        //    List<ProdProcScan> resList = new List<ProdProcScan>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        ctx.Database.CommandTimeout = 120;
        //        var query = ctx.ProdProcScans.Where(s => prods.Contains(s.ProdNumber));
        //        if (query != null && query.Count() > 0)
        //        {
        //            resList = query.ToList();
        //        }
        //    }
        //    return resList;
        //}




        ///// <summary>
        ///// 根据工单号查询工单状态的扫码记录
        ///// </summary>
        ///// <param name="prodNo"></param>
        ///// <returns></returns>
        //public List<ProdProcScan> SearchScanOnlyProdStatus(string prodNo)
        //{
        //    List<ProdProcScan> resList = new List<ProdProcScan>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        var query = from a in ctx.ProdProcScans
        //                    join b in ctx.StatusInfos on a.StatusInfoID equals b.ID into res1
        //                    from ab in res1
        //                    join c in ctx.StatusTypes on ab.StypeID equals c.ID into res2
        //                    from bc in res2
        //                    where a.ProdNumber == prodNo && bc.StypeName == "工单状态"
        //                    orderby a.ScanDate
        //                    select new { A = a, AB = ab, BC = bc };
        //        if (query != null && query.Count() > 0)
        //        {
        //            foreach (var item in query)
        //            {
        //                resList.Add(item.A);
        //            }
        //        }
        //    }
        //    return resList;
        //}

        ///// <summary>
        ///// 根据条件查询扫码记录
        ///// </summary>
        ///// <param name="prodNo">工单号</param>
        ///// <param name="mtoNo">计划跟踪号</param>
        ///// <param name="siteIds">站点</param>
        ///// <param name="client">客户代号</param>
        ///// <param name="saler">销售员</param>
        ///// <param name="beginDay">开始日期</param>
        ///// <param name="endDay">结束日期</param>
        ///// <returns></returns>
        //public List<ProdProcScanDTO> SearchScanForCondition(string prodNo, string mtoNo, List<int> siteIds, string client, string saler,
        //                                                            DateTime? beginDay, DateTime? endDay)
        //{
        //    List<ProdProcScanDTO> scanList = new List<ProdProcScanDTO>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        var query = from a in ctx.ProdProcScans
        //                    join b in ctx.TargetProdProcesses on a.ProdProcID equals b.ID into res1
        //                    from ab in res1
        //                    join c in ctx.ProdSchedules on a.ProdProcID equals c.ProdID into res2
        //                    from ac in res2.DefaultIfEmpty()
        //                    select new { A = a, AB = ab, AC = ac };
        //        if (prodNo != null && prodNo.Trim().Length > 0)
        //        {
        //            query = query.Where(q => q.A.ProdNumber.Contains(prodNo));
        //        }
        //        if (mtoNo != null && mtoNo.Trim().Length > 0)
        //        {
        //            query = query.Where(q => q.AB.MtoNumber.Contains(mtoNo));
        //        }
        //        if (siteIds != null && siteIds.Count > 0)
        //        {
        //            query = query.Where(q => siteIds.Contains(q.A.SiteInfoID));
        //        }
        //        if (client != null && client.Trim().Length > 0)
        //        {
        //            query = query.Where(q => q.AB.ClientCode.Contains(client));
        //        }
        //        if (saler != null && saler.Trim().Length > 0)
        //        {
        //            query = query.Where(q => q.AB.SalerName.Contains(saler));
        //        }
        //        if (beginDay.HasValue == true)
        //        {
        //            query = query.Where(q => ((DateTime)beginDay).Date <= DbFunctions.TruncateTime(q.A.ScanDate));
        //        }
        //        if (endDay.HasValue == true)
        //        {
        //            query = query.Where(q => DbFunctions.TruncateTime(q.A.ScanDate) <= ((DateTime)endDay).Date);
        //        }

        //        if (query != null && query.Count() > 0)
        //        {
        //            var tmpList = query.ToList();
        //            foreach (var scanItem in tmpList.Select(q => q.A).Distinct().ToList<ProdProcScan>())
        //            {
        //                ProdProcScanDTO scanBean = new ProdProcScanDTO();
        //                EntityTools.CopyEntity<ProdProcScan, ProdProcScanDTO>(scanItem, ref scanBean);

        //                var tmpQuery = tmpList.Where(q => q.A.ProdProcID == scanItem.ProdProcID);
        //                if (tmpQuery != null && tmpQuery.Count() > 0)
        //                {
        //                    foreach (var tmpItem in tmpQuery)
        //                    {
        //                        if (tmpItem.AB != null && tmpItem.AB.ID > 0)
        //                        {
        //                            if (scanBean.TargetProd is null || scanBean.TargetProd.ID <= 0)
        //                            {
        //                                scanBean.TargetProd = tmpItem.AB;
        //                            }
        //                        }

        //                        if (tmpItem.AC != null)
        //                        {
        //                            if (tmpItem.AC.LineID == 5 || tmpItem.AC.LineID == 10 || tmpItem.AC.LineID == 11 || tmpItem.AC.LineID == 12)
        //                            {
        //                                scanBean.ProdSchedule = tmpItem.AC;
        //                            }
        //                        }
        //                    }
        //                }
        //                scanList.Add(scanBean);
        //            }
        //        }
        //    }
        //    return scanList;
        //}

        /// <summary>
        /// 保存扫码记录
        /// </summary>
        /// <param name="target"></param>
        /// <param name="user"></param>
        /// <param name="site"></param>
        /// <param name="status"></param>
        /// <param name="scanQty"></param>
        /// <returns>该方法用于包装结束站点的扫码，该站点采用的扫码方式是分批扫码</returns>
        public int SaveProdProcessScan(TargetProdProcessDTO target, BaseUserModel user, SiteInfo site, StatusInfo status, decimal scanQty)
        {
            int count = 0;
            //取得服务器的系统时间
            DateTime tmpDay = GetCurrDateTime();
            using (MesDB ctx = new MesDB())
            {
                //取得工单该站点的已扫码数量 
                decimal clearQty = 0;
                var scanQuery = ctx.ProdProcScans.Where(s => s.ProdNumber == target.ProdNumber && s.SiteInfoID == site.ID);
                if (scanQuery != null && scanQuery.Count() > 0)
                {
                    clearQty = scanQuery.ToList<ProdProcScan>().Sum(s => s.ScanQty);
                }

                //取得扫码站点所在的大站的终点站
                SiteInfo tmpSite = this.GetEndSiteForSiteGroup(target.ProdNumber, site.SiteName);

                //如果工单  投产数量 <= 已经扫码数量 + 本次扫码数量，标记该工单完结
                Boolean isComp = target.ProdQty > clearQty + scanQty ? false : true;

                //TargetProdProcess tmpTarget = new TargetProdProcess();
                //EntityTools.CopyEntity(target, ref tmpTarget);
                //tmpTarget.ProdStatusID = status.ID;
                //tmpTarget.CurrSiteID = site.ID;
                //ctx.TargetProdProcesses.Attach(tmpTarget);
                //ctx.Entry<TargetProdProcess>(tmpTarget).State = System.Data.Entity.EntityState.Modified;

                //如果该工单标记了完结并且为最后一站，更新工单的当前站点、状态，并将本次的扫码时间当成工单的入库时间
                //if (isComp == true&&tmpSite.ID==site.ID)
                //{

                //订单扫码后，记录单据的生产状态
                TargetProdProcess tmpTarget = new TargetProdProcess();
                EntityTools.CopyEntity(target, ref tmpTarget);

                string beforeStr = EntityTools.GetPropNameAndValue(tmpTarget);
                tmpTarget.ProdStatusID = status.ID;
                tmpTarget.CurrSiteID = site.ID;
                string afterStr = EntityTools.GetPropNameAndValue(tmpTarget);

                MesLog meslog = this.InitMesLog("target_prod_process", target.ID, beforeStr, afterStr, "update", user.user_name, tmpDay);
                ctx.MesLogs.Add(meslog);

                ctx.TargetProdProcesses.Attach(tmpTarget);
                ctx.Entry<TargetProdProcess>(tmpTarget).State = System.Data.Entity.EntityState.Modified;
                //}

                //ctx.TargetProdProcesses.(tmpTarget);

                //保存扫码记录
                ProdProcScan scanBean = new ProdProcScan();
                scanBean.ProdProcID = target.ID;
                scanBean.ProdNumber = target.ProdNumber;
                scanBean.SiteInfoID = site.ID;
                scanBean.SiteName = site.SiteName;
                scanBean.StatusInfoID = status.ID;
                scanBean.StatusName = status.StatusValue;
                scanBean.ScanQty = scanQty;
                scanBean.ScanUser = user.user_name;
                scanBean.ScanDate = GetCurrDateTime();
                scanBean.IsComp = isComp == true ? 1 : 0;
                ctx.ProdProcScans.Add(scanBean);

                count = ctx.SaveChanges();
            }
            return count;
        }

        public SiteInfo GetEndSiteForSiteGroup(string prod, string site)
        {
            SiteInfo resBean = null;
            using (MesDB ctx = new MesDB())
            {
                SiteInfo tmpSite = null;
                var siteQuery = from a in ctx.SiteInfos
                                join b in ctx.SiteInfos on a.ParentID equals b.ID into res
                                from ab in res
                                where a.SiteName == site
                                select ab;
                if (siteQuery != null && siteQuery.Count() > 0)
                {
                    tmpSite = siteQuery.First();
                }

                if (tmpSite != null)
                {
                    var query = from a in ctx.TargetProdProcesses
                                join b in ctx.ProdProcSites on a.ID equals b.ProdProcID into res1
                                from ab in res1
                                join c in ctx.SiteGroups on ab.SiteGroupID equals c.ID into res2
                                from bc in res2
                                join d in ctx.SiteInfoGroups on bc.ID equals d.GroupID into res3
                                from cd in res3
                                join e in ctx.SiteInfos on cd.SiteID equals e.ID into res4
                                from de in res4
                                where a.ProdNumber == prod
                                orderby cd.Sort descending
                                select new { A = a, CD = cd, DE = de };
                    if (query != null && query.Count() > 0)
                    {
                        foreach (var item in query)
                        {
                            if (item.DE.ParentID == tmpSite.ID)
                            {
                                resBean = item.DE;
                                break;
                            }
                        }
                    }
                }


            }

            return resBean;
        }

        ///// <summary>
        ///// 保存扫码记录
        ///// </summary>
        ///// <param name="target"></param>
        ///// <param name="user"></param>
        ///// <param name="site"></param>
        ///// <param name="status"></param>
        ///// <returns>该方法只适用于其他站点扫码，包装结束站点不可用该方法</returns>
        //public int SaveProdProcessScan(TargetProdProcessDTO target, BaseUserModel user, SiteInfo site, StatusInfo status, int IsBatch = 0)
        //{
        //    int count = 0;
        //    DateTime tmpDay = this.GetCurrDateTime();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        var emplQuery = ctx.EmplInfos.AsQueryable();

        //        //取得扫码站点所在的大站的终点站
        //        SiteInfo tmpSite = this.GetEndSiteForSiteGroup(target.ProdNumber, site.SiteName);

        //        //更新工单的排单计划的完成状态
        //        var scheQuery = from a in ctx.ProdLineSettings
        //                        join b in ctx.ProdSchedules on a.ID equals b.LineID into res1
        //                        from ab in res1
        //                        join c in ctx.TargetProdProcesses on ab.ProdID equals c.ID into res2
        //                        from bc in res2
        //                        where (a.LastSiteID == site.ID || a.BeginSiteID == site.ID) && bc.ID == target.ID
        //                        select new { A = a, AB = ab };
        //        if (scheQuery != null && scheQuery.Count() > 0)
        //        {
        //            foreach (var item in scheQuery)
        //            {
        //                ProdSchedule scheBean = item.AB;
        //                if (item.A.LastSiteID == site.ID)
        //                {
        //                    scheBean.IsComp = 1;
        //                    scheBean.CompDate = tmpDay;
        //                }
        //                else if (item.A.BeginSiteID == site.ID && scheBean.Remark != null && scheBean.Remark.Equals("未收到"))
        //                {
        //                    scheBean.Remark = "";
        //                }
        //            }
        //        }


        //        TargetProdProcess tmpTarget = new TargetProdProcess();
        //        EntityTools.CopyEntity(target, ref tmpTarget);

        //        //为工单的变更写日志文件
        //        string beforeStr = EntityTools.GetPropNameAndValue(tmpTarget);
        //        tmpTarget.ProdStatusID = status.ID;
        //        tmpTarget.CurrSiteID = site.ID;
        //        //当扫码站点是包装开始时，根据扫码人员分配的生产线，决定工单所属的生产线
        //        if (site.ID == 19)
        //        {
        //            int compLineID = 0;
        //            if (emplQuery != null)
        //            {
        //                var compEmplQuery = emplQuery.Where(q => q.EmplNumber == user.user_name);
        //                var tmpList = new List<int>(new int[] { 6, 7, 8, 10, 11, 12, 15, 16 });
        //                if (compEmplQuery != null && compEmplQuery.Count() > 0)
        //                {
        //                    if (compEmplQuery.First().LineID == 5)
        //                    {
        //                        compLineID = compEmplQuery.First().LineID;
        //                    }
        //                    else if (tmpList.Contains(compEmplQuery.First().LineID))
        //                    {
        //                        compLineID = 16;
        //                    }
        //                }
        //            }

        //            if (compLineID > 0)
        //            {
        //                tmpTarget.CompLineID = compLineID;
        //            }
        //            else
        //            {
        //                throw new Exception("未能确定扫码员工所属生产线，中止扫码！");
        //            }
        //        }



        //        string afterStr = EntityTools.GetPropNameAndValue(tmpTarget);
        //        MesLog meslog = this.InitMesLog("target_prod_process", target.ID, beforeStr, afterStr, "update", user.user_name);
        //        ctx.MesLogs.Add(meslog);
        //        #region 如果是1的话就不做扫码记录，小弹窗保存了，如果是0就正常保存全部
        //        ////保存扫码记录
        //        ProdProcScan scanBean = new ProdProcScan();
        //        scanBean.ProdProcID = target.ID;
        //        scanBean.ProdNumber = target.ProdNumber;
        //        scanBean.SiteInfoID = site.ID;
        //        scanBean.SiteName = site.SiteName;
        //        scanBean.StatusInfoID = status.ID;
        //        scanBean.StatusName = status.StatusValue;
        //        scanBean.ScanQty = target.ProdQty ?? 0;
        //        scanBean.ScanUser = user.user_name;
        //        scanBean.ScanDate = GetCurrDateTime();
        //        //该方法会将扫码记录的工单完成状态设置为0，所以只适用于其他站点的扫码，不能用于包装结束站点
        //        scanBean.IsComp = 1;
        //        if (IsBatch == 0)
        //        {
        //            ctx.ProdProcScans.Add(scanBean);
        //        }
        //        #endregion
        //        //更新工单信息
        //        ctx.TargetProdProcesses.Attach(tmpTarget);
        //        ctx.Entry<TargetProdProcess>(tmpTarget).State = System.Data.Entity.EntityState.Modified;

        //        //更新工单每个大站的完成时间
        //        if (tmpSite != null && tmpSite.ID == site.ID)
        //        {
        //            var query = ctx.TargetPPCycle.Where(t => t.ProdNumber == target.ProdNumber);
        //            if (query != null && query.Count() > 0)
        //            {
        //                TargetPPCycle tmpBean = query.First();
        //                switch (site.ParentID)
        //                {
        //                    case 1:
        //                        tmpBean.SmtDate = scanBean.ScanDate;
        //                        break;
        //                    case 2:
        //                        tmpBean.WeldDate = scanBean.ScanDate;
        //                        break;
        //                    case 3:
        //                        tmpBean.TestDate = scanBean.ScanDate;
        //                        break;
        //                    case 4:
        //                        tmpBean.TestDate = scanBean.ScanDate;
        //                        break;
        //                    case 5:
        //                        tmpBean.PackDate = scanBean.ScanDate;
        //                        break;
        //                }
        //            }
        //        }

        //        count = ctx.SaveChanges();
        //    }
        //    return count;
        //}

        ///// <summary>
        ///// 保存异常订单
        ///// </summary>
        ///// <param name="order"></param>
        ///// <returns></returns>
        ///// <exception cref="Exception"></exception>
        //public int InsertExcepOrder(ExcepOrder order)
        //{
        //    if (order != null)
        //    {
        //        using (MesDB ctx = new MesDB())
        //        {
        //            ctx.ExcepOrder.Add(order);
        //            int count = ctx.SaveChanges();
        //            return count;
        //        }
        //    }
        //    else
        //    {
        //        throw new Exception("传入的异常订单资料为空！");
        //    }
        //}


        ///// <summary>
        ///// 将工单的暂停状态取消
        ///// </summary>
        ///// <param name="targetList">工单</param>
        ///// <param name="keeponStatus">取消暂停的状态码信息</param>
        ///// <returns></returns>
        ///// <exception cref="Exception"></exception>
        //public int KeepOnProdProcess(List<TargetProdProcessDTO> targetList, StatusInfo keeponStatus)
        //{
        //    if (targetList != null && targetList.Count > 0)
        //    {
        //        int count = 0;
        //        using (MesDB ctx = new MesDB())
        //        {
        //            foreach (var item in targetList)
        //            {
        //                TargetProdProcess tmpTarget = new TargetProdProcess();
        //                TargetProdProcess copyTarget = new TargetProdProcess();
        //                EntityTools.CopyEntity<TargetProdProcessDTO, TargetProdProcess>(item, ref tmpTarget);
        //                EntityTools.CopyEntity<TargetProdProcessDTO, TargetProdProcess>(item, ref copyTarget);

        //                //取消暂停时，工单的异常状态设置暂停前的状态
        //                tmpTarget.ErrStatusID = tmpTarget.TmpErrStatusID ?? 0;
        //                tmpTarget.TmpErrStatusID = 0;
        //                ctx.TargetProdProcesses.Attach(tmpTarget);
        //                ctx.Entry(tmpTarget).State = System.Data.Entity.EntityState.Modified;

        //                //取消暂停时，扫码记录中的状态为取消暂停状态
        //                ProdProcScan tmpScan = new ProdProcScan();
        //                tmpScan.ProdProcID = tmpTarget.ID;
        //                tmpScan.ProdNumber = tmpTarget.ProdNumber;
        //                tmpScan.SiteInfoID = tmpTarget.CurrSiteID;
        //                tmpScan.SiteName = ctx.SiteInfos.Where(s => s.ID == tmpTarget.CurrSiteID).First().SiteName;
        //                tmpScan.StatusInfoID = keeponStatus.ID;
        //                tmpScan.StatusName = keeponStatus.StatusValue;
        //                tmpScan.ScanQty = tmpTarget.ProdQty ?? 0;
        //                tmpScan.ScanDate = DateTime.Now;
        //                tmpScan.ScanUser = MainFrm.LoginUser.user_name;
        //                ctx.ProdProcScans.Add(tmpScan);

        //                MesLog mesLog = new MesLog();
        //                mesLog.TableName = "target_prod_process";
        //                mesLog.TableID = tmpTarget.ID;
        //                mesLog.BeforeData = EntityTools.GetPropNameAndValue(copyTarget);
        //                mesLog.AfterData = EntityTools.GetPropNameAndValue(tmpTarget);
        //                mesLog.ChangeType = "update";
        //                mesLog.ChangeUser = MainFrm.LoginUser.user_name;
        //                mesLog.ChangeDate = DateTime.Now;
        //                ctx.MesLogs.Add(mesLog);

        //                count = ctx.SaveChanges();
        //            }
        //        }
        //        return count;
        //    }
        //    else
        //    {
        //        throw new Exception("没有任何可以保存的资料！");
        //    }
        //}


        ///// <summary>
        ///// 将工单暂停
        ///// </summary>
        ///// <param name="targetList">工单</param>
        ///// <param name="pauseStatus">暂停的状态码信息</param>
        ///// <returns></returns>
        ///// <exception cref="Exception"></exception>
        //public int PauseProdProcess(List<TargetProdProcessDTO> targetList, StatusInfo pauseStatus)
        //{
        //    if (targetList != null && targetList.Count > 0)
        //    {
        //        int count = 0;
        //        using (MesDB ctx = new MesDB())
        //        {
        //            foreach (var item in targetList)
        //            {
        //                TargetProdProcess tmpTarget = new TargetProdProcess();
        //                TargetProdProcess copyTarget = new TargetProdProcess();
        //                EntityTools.CopyEntity<TargetProdProcessDTO, TargetProdProcess>(item, ref tmpTarget);
        //                EntityTools.CopyEntity<TargetProdProcessDTO, TargetProdProcess>(item, ref copyTarget);


        //                tmpTarget.TmpErrStatusID = tmpTarget.ErrStatusID;
        //                tmpTarget.ErrStatusID = pauseStatus.ID;
        //                ctx.TargetProdProcesses.Attach(tmpTarget);
        //                ctx.Entry(tmpTarget).State = System.Data.Entity.EntityState.Modified;

        //                ProdProcScan tmpScan = new ProdProcScan();
        //                tmpScan.ProdProcID = tmpTarget.ID;
        //                tmpScan.ProdNumber = tmpTarget.ProdNumber;
        //                tmpScan.SiteInfoID = tmpTarget.CurrSiteID;
        //                tmpScan.SiteName = ctx.SiteInfos.Where(s => s.ID == tmpTarget.CurrSiteID).First().SiteName;
        //                tmpScan.StatusInfoID = pauseStatus.ID;
        //                tmpScan.StatusName = pauseStatus.StatusValue;
        //                tmpScan.ScanQty = tmpTarget.ProdQty ?? 0;
        //                tmpScan.ScanDate = DateTime.Now;
        //                tmpScan.ScanUser = MainFrm.LoginUser.user_name;
        //                ctx.ProdProcScans.Add(tmpScan);

        //                MesLog mesLog = new MesLog();
        //                mesLog.TableName = "target_prod_process";
        //                mesLog.TableID = tmpTarget.ID;
        //                mesLog.BeforeData = EntityTools.GetPropNameAndValue(copyTarget);
        //                mesLog.AfterData = EntityTools.GetPropNameAndValue(tmpTarget);
        //                mesLog.ChangeType = "update";
        //                mesLog.ChangeUser = MainFrm.LoginUser.user_name;
        //                mesLog.ChangeDate = DateTime.Now;
        //                ctx.MesLogs.Add(mesLog);

        //                count = ctx.SaveChanges();
        //            }
        //        }
        //        return count;
        //    }
        //    else
        //    {
        //        throw new Exception("没有任何可以保存的资料！");
        //    }
        //}


        ///// <summary>
        ///// 判断工单中某一站点所在的大站的结束站
        ///// </summary>
        ///// <param name="prod"></param>
        ///// <param name="site"></param>
        ///// <returns></returns>
        //public SiteInfo GetEndSiteForSiteGroup(string prod, string site)
        //{
        //    SiteInfo resBean = null;
        //    using (MesDB ctx = new MesDB())
        //    {
        //        SiteInfo tmpSite = null;
        //        var siteQuery = from a in ctx.SiteInfos
        //                        join b in ctx.SiteInfos on a.ParentID equals b.ID into res
        //                        from ab in res
        //                        where a.SiteName == site
        //                        select ab;
        //        if (siteQuery != null && siteQuery.Count() > 0)
        //        {
        //            tmpSite = siteQuery.First();
        //        }

        //        if (tmpSite != null)
        //        {
        //            var query = from a in ctx.TargetProdProcesses
        //                        join b in ctx.ProdProcSites on a.ID equals b.ProdProcID into res1
        //                        from ab in res1
        //                        join c in ctx.SiteGroups on ab.SiteGroupID equals c.ID into res2
        //                        from bc in res2
        //                        join d in ctx.SiteInfoGroups on bc.ID equals d.GroupID into res3
        //                        from cd in res3
        //                        join e in ctx.SiteInfos on cd.SiteID equals e.ID into res4
        //                        from de in res4
        //                        where a.ProdNumber == prod
        //                        orderby cd.Sort descending
        //                        select new { A = a, CD = cd, DE = de };
        //            if (query != null && query.Count() > 0)
        //            {
        //                foreach (var item in query)
        //                {
        //                    if (item.DE.ParentID == tmpSite.ID)
        //                    {
        //                        resBean = item.DE;
        //                        break;
        //                    }
        //                }
        //            }
        //        }


        //    }
        //    return resBean;
        //}


        //public List<Tuple<SiteGroup, SiteInfoGroup, SiteInfo>> SearchSiteGroupForProd(string prod)
        //{
        //    List<Tuple<SiteGroup, SiteInfoGroup, SiteInfo>> resList = new List<Tuple<SiteGroup, SiteInfoGroup, SiteInfo>>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        var query = from a in ctx.TargetProdProcesses
        //                    join b in ctx.ProdProcSites on a.ID equals b.ProdProcID into res1
        //                    from ab in res1
        //                    join c in ctx.SiteGroups on ab.SiteGroupID equals c.ID into res2
        //                    from bc in res2
        //                    join d in ctx.SiteInfoGroups on bc.ID equals d.GroupID into res3
        //                    from cd in res3
        //                    join e in ctx.SiteInfos on cd.SiteID equals e.ID into res4
        //                    from de in res4
        //                    where a.ProdNumber == prod
        //                    select new { BC = bc, CD = cd, DE = de };
        //        if (query != null && query.Count() > 0)
        //        {
        //            foreach (var item in query)
        //            {
        //                resList.Add(new Tuple<SiteGroup, SiteInfoGroup, SiteInfo>(item.BC, item.CD, item.DE));
        //            }
        //        }
        //    }
        //    return resList;
        //}


        //public int UpdateTargetCompLine(List<TargetProdProcess> targetList)
        //{
        //    int count = 0;
        //    DateTime tmpDay = this.GetCurrDateTime();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        foreach (var targetBean in targetList)
        //        {
        //            var query = ctx.TargetProdProcesses.Where(q => q.ProdNumber == targetBean.ProdNumber);
        //            if (query != null && query.Count() > 0)
        //            {
        //                string oldMsg = EntityTools.GetPropNameAndValue(query.First());
        //                query.First().CompLineID = targetBean.CompLineID;
        //                string newMsg = EntityTools.GetPropNameAndValue(query.First());
        //                MesLog mesLog = this.InitMesLog("target_prod_process", targetBean.ID, oldMsg, newMsg, "update", MainFrm.LoginUser.user_name, tmpDay);
        //                ctx.MesLogs.Add(mesLog);
        //            }
        //        }

        //        count = ctx.SaveChanges();
        //    }
        //    return count;
        //}


        ///// <summary>
        ///// 根据工单ID查询工单的流程组
        ///// </summary>
        ///// <param name="prodIds"></param>
        ///// <returns></returns>
        //public List<ProdProcSite> SearchProdProcSite(List<int> prodIds)
        //{
        //    List<ProdProcSite> resList = new List<ProdProcSite>();
        //    using (MesDB ctx = new MesDB())
        //    {
        //        var query = ctx.ProdProcSites.Where(q => prodIds.Contains(q.ProdProcID));
        //        resList = query != null && query.Count() > 0 ? query.ToList() : new List<ProdProcSite>();
        //    }
        //    return resList;
        //}


        ///// <summary>
        ///// 查询所有工单集体计件单价
        ///// </summary>
        ///// <returns></returns>
        //public List<Prod_price_projectDTO> SearchAllProdSitePrice()
        //{
        //    List<Prod_price_projectDTO> resList = new List<Prod_price_projectDTO>();
        //    using (SqlSugarClient ctx = SqlSugares.GetInstance())
        //    {
        //        var query = ctx.Queryable<Prod_price_project, Prod_price_detail>(
        //                        (p, d) => new JoinQueryInfos(JoinType.Left, p.id == d.prod_price_project_id)
        //                    ).Select((p, d) => new { P = p, D = d }).ToList();
        //        if (query != null && query.Count() > 0)
        //        {
        //            var tmpList = query.Select(q => q.P.id).Distinct().ToList();
        //            foreach (var tmpID in tmpList)
        //            {
        //                var tmpQuery = query.Where(q => q.P.id == tmpID);
        //                if (tmpQuery != null && tmpQuery.Count() > 0)
        //                {
        //                    Prod_price_projectDTO tmpBean = new Prod_price_projectDTO();
        //                    EntityTools.CopyEntity<Prod_price_project, Prod_price_projectDTO>(tmpQuery.First().P, ref tmpBean);

        //                    tmpBean.price_detail_list = new List<Prod_price_detail>();
        //                    tmpBean.price_detail_list.AddRange(tmpQuery.Select(q => q.D));

        //                    resList.Add(tmpBean);
        //                }
        //            }
        //        }
        //    }
        //    return resList;
        //}

        /// <summary>
        /// 查询工单扫码信息
        /// </summary>
        /// <param name="prod">工单号</param>
        /// <param name="mto">计划跟踪单</param>
        /// <param name="parentSite">大站名称</param>
        /// <param name="dept">工单所在线别</param>
        /// <param name="client">客户</param>
        /// <param name="saler">销售员</param>
        /// <param name="compFlag">状态标志，1为撤销；2为未上线；3为生产中；4为已完成</param>
        /// <param name="compBeginDay">查询开始时间，针对包装入库站的扫码时间</param>
        /// <param name="compEndDate">查询结束时间，针对包装入库站的扫码时间</param>
        /// <param name="pageIndex">显示页码</param>
        /// <param name="pageSize">每页显示的数量</param>
        /// <param name="totalPage">查询结果的总工单数</param>
        /// <returns></returns>
        public List<TargetProdProcessDTO> SearchProdScanForProcedure(string prod, string mto, string parentSite, string dept, string client, string saler,
                                                    int compFlag, string compBeginDay, string compEndDate, int pageIndex, int pageSize, ref int totalPage)
        {
            List<TargetProdProcessDTO> resList = new List<TargetProdProcessDTO>();
            int tmpInt = 0;
            decimal tmpDec = 0;
            DateTime tmpDate = new DateTime();
            //建立上下文
            using (SqlSugarClient ctx = SqlSugares.GetInstance())
            {
                //设定执行存储过程的参数
                var outParam = new SugarParameter("@total_count", tmpInt, System.Data.DbType.Int32, ParameterDirection.Output);
                var parameters = new List<SugarParameter>
                {
                    new SugarParameter("@prod_number",prod),
                    new SugarParameter("@mto_number",mto),
                    new SugarParameter("@parent_site",parentSite),
                    new SugarParameter("@dept",dept),
                    new SugarParameter("@client_code",client),
                    new SugarParameter("@saler_name",saler),
                    new SugarParameter("@comp_flag",compFlag),
                    new SugarParameter("@begin_comp_date",compBeginDay),
                    new SugarParameter("@end_comp_date",compEndDate),
                    new SugarParameter("@page_index",pageIndex),
                    new SugarParameter("@page_size",pageSize),
                    outParam
                };

                //执行存储过程，并将存储过程的结果用DataTable返回
                var tmpDt = ctx.Ado.UseStoredProcedure().GetDataTable("Proc_Search_ProdScan", parameters);
                totalPage = int.TryParse(outParam.Value.ToString(), out tmpInt) ? tmpInt : 0;

                //将DataTable的数据转换成实体类
                if (tmpDt != null && tmpDt.Rows.Count > 0)
                {
                    string filterStr = "";
                    //先提取工单信息，将信息放到工单实体类TargetProdProcessDTO中
                    var prodDt = tmpDt.DefaultView.ToTable(true, new string[] { "prod_id", "prod_number", "mo_number", "mto_number", "goods_number", "goods_name", "goods_spe", "goods_length",
                                                                                    "order_qty", "prod_qty", "client_code", "saler_name", "prod_status", "urgent_status", "err_status",
                                                                                    "curr_site_id", "dept_id", "comp_line_id", "prod_sort", "group_id", "group_name",
                                                                                    "source_pp_id", "order_date", "plan_date", "max_date"});
                    foreach (DataRow prodRow in prodDt.Rows)
                    {
                        TargetProdProcessDTO prodBean = new TargetProdProcessDTO
                        {
                            ID = prodRow["prod_id"] != DBNull.Value && int.TryParse(prodRow["prod_id"].ToString(), out tmpInt) ? tmpInt : 0,
                            ProdNumber = prodRow["prod_number"] != DBNull.Value ? prodRow["prod_number"].ToString() : "",
                            MoNumber = prodRow["mo_number"] != DBNull.Value ? prodRow["mo_number"].ToString() : "",
                            MtoNumber = prodRow["mto_number"] != DBNull.Value ? prodRow["mto_number"].ToString() : "",
                            GoodsNumber = prodRow["goods_number"] != DBNull.Value ? prodRow["goods_number"].ToString() : "",
                            GoodsName = prodRow["goods_name"] != DBNull.Value ? prodRow["goods_name"].ToString() : "",
                            GoodsSpe = prodRow["goods_spe"] != DBNull.Value ? prodRow["goods_spe"].ToString() : "",
                            GoodsLength = prodRow["goods_length"] != DBNull.Value && decimal.TryParse(prodRow["goods_length"].ToString(), out tmpDec) ? tmpDec : 0,
                            OrderQty = prodRow["order_qty"] != DBNull.Value && decimal.TryParse(prodRow["order_qty"].ToString(), out tmpDec) ? tmpDec : 0,
                            ProdQty = prodRow["prod_qty"] != DBNull.Value && decimal.TryParse(prodRow["prod_qty"].ToString(), out tmpDec) ? tmpDec : 0,
                            ClientCode = prodRow["client_code"] != DBNull.Value ? prodRow["client_code"].ToString() : "",
                            SalerName = prodRow["saler_name"] != DBNull.Value ? prodRow["saler_name"].ToString() : "",
                            ProdStatusID = prodRow["prod_status"] != DBNull.Value && int.TryParse(prodRow["prod_status"].ToString(), out tmpInt) ? tmpInt : 0,
                            UrgentStatusID = prodRow["urgent_status"] != DBNull.Value && int.TryParse(prodRow["urgent_status"].ToString(), out tmpInt) ? tmpInt : 0,
                            ErrStatusID = prodRow["err_status"] != DBNull.Value && int.TryParse(prodRow["err_status"].ToString(), out tmpInt) ? tmpInt : 0,
                            CurrSiteID = prodRow["curr_site_id"] != DBNull.Value && int.TryParse(prodRow["curr_site_id"].ToString(), out tmpInt) ? tmpInt : 0,
                            DeptId = prodRow["dept_id"] != DBNull.Value && int.TryParse(prodRow["dept_id"].ToString(), out tmpInt) ? tmpInt : 0,
                            CompLineID = prodRow["comp_line_id"] != DBNull.Value && int.TryParse(prodRow["comp_line_id"].ToString(), out tmpInt) ? tmpInt : 0
                        };
                        prodBean.ProdSort = prodRow["prod_sort"] != DBNull.Value && int.TryParse(prodRow["prod_sort"].ToString(), out tmpInt) ? tmpInt : 0;
                        prodBean.SiteGroup = new SiteGroupDTO
                        {
                            ID = prodRow["group_id"] != DBNull.Value && int.TryParse(prodRow["group_id"].ToString(), out tmpInt) ? tmpInt : 0,
                            GroupName = prodRow["group_name"] != DBNull.Value ? prodRow["group_name"].ToString() : ""
                        };
                        //prodBean.SourceCycle = new SourcePPCycle
                        //{
                        //    ID = prodRow["source_pp_id"] != DBNull.Value && int.TryParse(prodRow["source_pp_id"].ToString(), out tmpInt) ? tmpInt : 0,
                        //    OrderDate = prodRow["order_date"] != DBNull.Value && DateTime.TryParse(prodRow["order_date"].ToString(), out tmpDate) ? tmpDate : new DateTime(1900, 1, 1),
                        //    PlanDate = prodRow["plan_date"] != DBNull.Value && DateTime.TryParse(prodRow["plan_date"].ToString(), out tmpDate) ? (DateTime?)tmpDate : null,
                        //    MaxDate = prodRow["max_date"] != DBNull.Value && DateTime.TryParse(prodRow["max_date"].ToString(), out tmpDate) ? (DateTime?)tmpDate : null,
                        //};

                        //根据不同的工单，找到对应的流程信息，并将流程对应的所有站点转换成实体类，并与工单实体类做绑定
                        filterStr = "prod_id = " + prodBean.ID.ToString();
                        tmpDt.DefaultView.RowFilter = filterStr;
                        tmpDt.DefaultView.Sort = "prod_id,site_sort";
                        var siteDt = tmpDt.DefaultView.ToTable(true, new string[] { "site_id", "site_code", "site_name", "site_parent_id", "cal_point", "site_sort", "site_is_last" });
                        if (siteDt != null && siteDt.Rows.Count > 0)
                        {
                            prodBean.SiteGroup.SiteInfoList = new List<SiteInfoGroupDTO>();
                            foreach (DataRow siteRow in siteDt.Rows)
                            {
                                SiteInfoGroupDTO tmpBean = new SiteInfoGroupDTO
                                {
                                    GroupID = prodBean.SiteGroup.ID,
                                    SiteID = siteRow["site_id"] != DBNull.Value && int.TryParse(siteRow["site_id"].ToString(), out tmpInt) ? tmpInt : 0,
                                    Sort = siteRow["site_sort"] != DBNull.Value && int.TryParse(siteRow["site_sort"].ToString(), out tmpInt) ? tmpInt : 0,
                                    IsLast = siteRow["site_is_last"] != DBNull.Value && int.TryParse(siteRow["site_is_last"].ToString(), out tmpInt) ? tmpInt : 0,
                                    SiteInfo = new SiteInfo
                                    {
                                        ID = siteRow["site_id"] != DBNull.Value && int.TryParse(siteRow["site_id"].ToString(), out tmpInt) ? tmpInt : 0,
                                        SiteCode = siteRow["site_code"] != DBNull.Value ? siteRow["site_code"].ToString() : "",
                                        SiteName = siteRow["site_name"] != DBNull.Value ? siteRow["site_name"].ToString() : "",
                                        ParentID = siteRow["site_parent_id"] != DBNull.Value && int.TryParse(siteRow["site_parent_id"].ToString(), out tmpInt) ? tmpInt : 0,
                                        CalPoint = siteRow["cal_point"] != DBNull.Value ? siteRow["cal_point"].ToString() : ""
                                    }
                                };
                                prodBean.SiteGroup.SiteInfoList.Add(tmpBean);
                            }

                        }

                        filterStr = "prod_id = " + prodBean.ID.ToString();
                        tmpDt.DefaultView.RowFilter = filterStr;
                        tmpDt.DefaultView.Sort = "scan_date";
                        var scanDt = tmpDt.DefaultView.ToTable();
                        if (scanDt != null && scanDt.Rows.Count > 0)
                        {
                            prodBean.scanList = new List<ProdProcScan>();
                            foreach (DataRow scanRow in scanDt.Rows)
                            {
                                ProdProcScan scanBean = new ProdProcScan
                                {
                                    ID = scanRow["scan_id"] != DBNull.Value && int.TryParse(scanRow["scan_id"].ToString(), out tmpInt) ? tmpInt : 0,
                                    ProdNumber = prodBean.ProdNumber,
                                    ProdProcID = prodBean.ID,
                                    SiteInfoID = scanRow["site_id"] != DBNull.Value && int.TryParse(scanRow["site_id"].ToString(), out tmpInt) ? tmpInt : 0,
                                    SiteName = scanRow["site_name"] != DBNull.Value ? scanRow["site_name"].ToString() : "",
                                    ScanQty = scanRow["scan_qty"] != DBNull.Value && decimal.TryParse(scanRow["scan_qty"].ToString(), out tmpDec) ? tmpDec : 0,
                                    IsComp = scanRow["site_is_last"] != DBNull.Value && int.TryParse(scanRow["site_is_last"].ToString(), out tmpInt) ? tmpInt : 0,
                                    ScanUser = scanRow["scan_user"] != DBNull.Value ? scanRow["scan_user"].ToString() : "",
                                    ScanDate = scanRow["scan_date"] != DBNull.Value && DateTime.TryParse(scanRow["scan_date"].ToString(), out tmpDate) ? tmpDate : new DateTime(1900, 1, 1),
                                    RealName = scanRow["real_name"] != DBNull.Value ? scanRow["real_name"].ToString() : ""
                                };
                                prodBean.scanList.Add(scanBean);
                            }
                        }
                        resList.Add(prodBean);
                    }
                }
            }
            return resList;
        }


        //public System.Data.DataTable SearchProdScanDtForProcedure(string prod, string mto, string parentSite, string dept, string client, string saler,
        //                                                int compFlag, string compBeginDay, string compEndDate, int pageIndex, int pageSize, ref int totalPage)
        //{
        //    System.Data.DataTable resDt = new System.Data.DataTable();
        //    return resDt;
        //}
    }
}
